package com.ruoyi.management.file.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Value("${custom.file.bucketName}")
    private String bucketName;

    @RequestMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file,
                       @RequestParam("businessId") String businessId) throws IOException {
        InputStream inputStream = file.getInputStream();
        OutputStream os = null;
        try {
            String path = bucketName;
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件

            String filePath = path + File.separator
                    + DateTimeFormatter.ofPattern("yyyy"+ File.separator+"MM"+ File.separator+"dd").format(LocalDate.now())
                    + File.separator;

            File tempFile = new File(filePath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }

            os = new FileOutputStream(filePath
                    + System.currentTimeMillis() + file.getOriginalFilename());
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return AjaxResult.success();
    }
}
